import React from 'react'
import TextField from 'material-ui/TextField';

import QuestionAdder from './QuestionAdder';
import QuestionCards from './QuestionCards';
import SurveySubmitter from './SurveySubmitter';
import {myStyles} from '../utils';


export default class CreateSurvey extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            title: 'Sample Title',
            questions: [{
                title: 'Sample Question',
                options: [{text: 'Option1'}, {text: 'Option2'},]
            }, {
                title: 'Sample Question2',
                options: [{text: 'Option1'}, {text: 'Option2'},]
            }], //{title:'',options:[{text: ''}]}
        }

        this.handleTitleChange = this.handleTitleChange.bind(this)
        this.addQuestion = this.addQuestion.bind(this)
        this.removeQuestion = this.removeQuestion.bind(this)
        this.addOption = this.addOption.bind(this)
        this.removeOption = this.removeOption.bind(this)
    }

    handleTitleChange(e) {
        const t = e.target
        this.setState({
            title: t.value
        })
    }

    addQuestion(title) {
        const questions = this.state.questions
        questions.push({
            title: title,
            options: [],
        })
        this.setState({questions})
    }

    addOption(questionIndex,optionText){
        const questions = [...this.state.questions]
        questions[questionIndex].options.push({text: optionText})
        this.setState({questions})
    }

    removeOption(questionIndex,optionIndex){
        const questions = [...this.state.questions]
        questions[questionIndex].options.splice(optionIndex,1)
        this.setState({questions})
    }

    removeQuestion(index){
        console.info('Remove question index: '+index)
        const questions = [...this.state.questions]
        questions.splice(index,1)
        this.setState({
            questions
        })
    }

    render() {
        return (
            <div style={myStyles.container} >
                <h1>{this.state.title}</h1>

                <TextField
                    hintText="主题"
                    floatingLabelText="填写问卷主题"
                    name='title'
                    value={this.state.title}
                    onChange={this.handleTitleChange} />

                <QuestionCards
                    questions={this.state.questions}
                    removeQuestion={this.removeQuestion}
                    addOption={this.addOption}
                    removeOption={this.removeOption} />

                <QuestionAdder addQuestion={this.addQuestion} />

                <SurveySubmitter survey={this.state} />
            </div>
        )
    }
}